package com.dt.dubai.core.email.service;

import com.dt.dubai.core.email.bean.MailBean;
import com.dt.dubai.core.email.service.ser.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class MailServiceImp implements MailService {

    private static final Logger logger = LoggerFactory.getLogger(MailServiceImp.class);
    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    /*@Async*/
    @Override
    public void sendTextMail(MailBean mailBean) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from); // 发送人的邮箱
        message.setSubject(mailBean.getTitle()); //标题
        message.setTo(mailBean.getTo()); //发给谁  对方邮箱
        message.setText(mailBean.getContent()); //内容
        try {
            javaMailSender.send(message); //发送
        } catch (MailException e) {
            logger.error("发送失败："+e.getMessage());
           e.printStackTrace();
           /* throw new SystemException("邮件发送失败");*/
        }
    }
    /*@Async*/
    @Override
    public void sendHtmlMail(MailBean mailBean, boolean isShowHtml){
        try {

            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //是否发送的邮件是富文本（附件，图片，html等）
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);//true：开启带附件
            messageHelper.setFrom(from);// 发送人的邮箱
            messageHelper.setTo(mailBean.getTo());//发给谁  对方邮箱
            messageHelper.setSubject(mailBean.getTitle());//标题
            messageHelper.setText(mailBean.getContent(),isShowHtml);//false，显示原始html代码，无效果


            //判断是否有附件等
            if(mailBean.getMaps() != null && mailBean.getMaps().size() > 0){
               mailBean.getMaps().entrySet().stream().forEach(entrySet -> {
                    try {
                        File file = new File(String.valueOf(entrySet.getValue()));
                        if(file.exists()){
                            logger.error("存在");
                            messageHelper.addAttachment(entrySet.getKey(), new FileSystemResource(file));
                        }
                    } catch (Exception e) {
                        logger.error("附件发送失败"+e.getMessage());
                    }
                });
            }
            //发送
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
           logger.error("富文本邮件发送失败->message:{}",e.getMessage());
        }

    }
   /* @Async*/
    @Override
    public void sendTemplateMail(MailBean mailBean) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            messageHelper.setFrom(from);// 发送人的邮箱
            messageHelper.setTo(mailBean.getTo());//发给谁  对方邮箱
            messageHelper.setSubject(mailBean.getTitle()); //标题
            //使用模板thymeleaf
            //Context是导这个包import org.thymeleaf.context.Context;
            Context context = new Context();
            //定义模板数据
            context.setVariables(mailBean.getMaps());
            //获取thymeleaf的html模板
            String emailContent = templateEngine.process("mailBean",context); //指定模板路径
            messageHelper.setText(emailContent,true);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            logger.error("模板邮件发送失败->message:{}",e.getMessage());

        }

    }
}